package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Notice;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/notice")
public class NoticeController {
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/list")
    public String list(Model model, QueryObject qo){
        PageInfo<Notice> pageInfo = noticeService.query(qo);
        PageInfo<Notice> noticePageInfo = noticeService.selectIsRead(pageInfo);
        model.addAttribute("pageInfo", noticePageInfo);
        List<Employee> employees = employeeService.selectAll();
        model.addAttribute("qo", qo);
        model.addAttribute("employees", employees);
        return "notice/list";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(Long id){
        try {
            noticeService.delete(id);
            return new JsonResult();
        } catch(Exception e) {
            e.printStackTrace();
            return new JsonResult("操作失败",false);
        }

    }

    @RequestMapping("/input")
    public String input(Long id,Model model){
        if(id != null){
            Notice notice = noticeService.selectByPrimaryKey(id);
            model.addAttribute("notice", notice);
        }
        return "notice/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(Model model,@ModelAttribute("qo") Notice notice,Long id){
        try {
            if(id != null){
                noticeService.update(notice);
            }else {
                noticeService.insert(notice);
            }
            return new JsonResult();
        } catch(Exception e) {
            e.printStackTrace();
            return new JsonResult(e.getMessage(),false);
        }

    }

    @RequestMapping("/show")
    public String show(Model model,Long id){
        noticeService.show(id);
        Notice notice = noticeService.selectByPrimaryKey(id);
        model.addAttribute("notice", notice);
        model.addAttribute("date", new Date());
        return "notice/show";
    }
}
